package com.plm.mqshequ.nosql;

import com.plm.mqshequ.entity.Reply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Limi
 * @create 2019-01-19 22:54
 */
@Repository
public class MongoReplyOps {

    @Autowired
    private MongoTemplate template;

    /**
     * 保存回复
     */
    public void save(Reply reply) {
        template.save(reply);
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    public Reply findById(String id) {
        Query query = new Query(Criteria.where("status").is("0").and("_id").is(id));
        return template.findOne(query, Reply.class);
    }

    public Reply findAllById(String id) {
        Query query = new Query(Criteria.where("_id").is(id));
        return template.findOne(query, Reply.class);
    }

    /**
     * 根据用户Id查询
     * @param uid
     * @return
     */
    public List<Reply> findByUid(String uid) {
        Query query = new Query(Criteria.where("status").is("0").and("uid").is(uid));
        return template.find(query, Reply.class);
    }

    /**
     * 查询最近10条回复
     * @param uid
     * @return
     */
    public List<Reply> findByUidRecent(String uid) {
        Query query = new Query(Criteria.where("status").is("0").and("uid").is(uid));
        //按创建时间降序排序
        Sort sort = new Sort(Sort.Direction.DESC, "replyTime");
        query.with(sort);
        //设置起始数
        query.skip(0);
        //设置查询条数
        query.limit(10);
        return template.find(query, Reply.class);
    }

    /**
     * 根据帖子Id查询
     * @param postId
     * @return
     */
    public List<Reply> findByPostId(String postId) {
        Query query = new Query(
                Criteria.where("status").is("0")
                        .and("postId").is(postId)
        );
        return template.find(query, Reply.class);
    }

    /**
     * 根据实体更新
     * @param reply
     */
    public void update(Reply reply){
        Query query = new Query(Criteria.where("status").is("0").and("_id").is(reply.get_id()));
        Update update = new Update();
        update.set("accept", reply.getAccept())
                .set("status", reply.getStatus());
        template.updateFirst(query, update, Reply.class);
    }

    /**
     * 根据id删除回复
     * @param id
     */
    public void remove(String id){
        Query query = new Query(Criteria.where("_id").is(id));
        template.remove(query, Reply.class);
    }

}
